package blackstar.agent.jmx;

import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;
import javax.management.ObjectName;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MBeanUtils
{
	private final static Log LOGGER = LogFactory.getLog(MBeanUtils.class);

	public final static String ID_BEAN_NAME = "BlackStar:name=ID";

	public final static String DOMAIN = "BlackStar";

	public static boolean registMBean(String name, Object bean)
	{
		String beanName = DOMAIN + ":name=" + name;
		return doRegistMBean(beanName, bean);
	}

	public static boolean registMBean(String name, String type, Object bean)
	{
		String beanName = DOMAIN + ":type=" + type + ",name=" + name;
		return doRegistMBean(beanName, bean);
	}

	private static boolean doRegistMBean(String beanName, Object bean)
	{
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		try
		{
			server.registerMBean(bean, new ObjectName(beanName));
			LOGGER.info("Regist Bean[" + bean + "] Bean with Name[" + beanName
					+ "] Success");

			return true;
		} catch (Exception e)
		{
			LOGGER.error("Regist Bean[" + bean + "] Bean with Name[" + beanName
					+ "] Failed", e);

			return false;
		}
	}

	public static void unregistMBean(String name)
	{
		String beanName = DOMAIN + ":name=" + name;
		doUnregistMBean(beanName);
	}

	public static void unregistMBean(String name, String type)
	{
		String beanName = DOMAIN + ":type=" + type + ",name=" + name;
		doUnregistMBean(beanName);
	}

	private static void doUnregistMBean(String beanName)
	{
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		try
		{
			server.unregisterMBean(new ObjectName(beanName));
			LOGGER.info("Unregister Bean with Name[" + beanName + "] Success");
		} catch (Exception e)
		{
			LOGGER.error("Unregister Bean  with Name[" + beanName + "] Failed",
					e);
		}
	}
}
